﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

namespace VSM.Business.Purchasing
{
    public partial class MRP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Title = "MRP";
            try
            {
                if (!IsPostBack)
                {
                    LoadForeCastList();
                    BindData(BuildContents(null));
                    this.txtRunDate.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
                    this.txtRunDate.Enabled = false;
                    this.txtDateFrom.Text = DateTime.Now.ToString("MM/yyyy");
                    this.txtDateTo.Text = DateTime.Now.ToString("MM/yyyy");
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtContent"></param>
        /// <returns></returns>
        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable("FCT1");
            try
            {
                dt.Columns.Add("No");
                dt.Columns.Add("U_ModelSales");
                dt.Columns.Add("U_ProductSales");
                dt.Columns.Add("ModelName");
                dt.Columns.Add("ProductName");
                dt.Columns.Add("VendorCode");
                dt.Columns.Add("VendorName");
                dt.Columns.Add("ForeCastQty");
                dt.Columns.Add("MinStock");
                dt.Columns.Add("SOQty");
                dt.Columns.Add("POQty");
                dt.Columns.Add("InHand");
                dt.Columns.Add("MRP");
                if (dtContent != null)
                {
                    foreach (DataRow r in dtContent.Rows)
                    {
                        double fc, minStock, soQty, poQty, inHand, mrp;
                        fc = double.Parse(r["ForeCast"].ToString().Length == 0 ? "0" : r["ForeCast"].ToString());
                        minStock = double.Parse(r["MinStock"].ToString().Length == 0 ? "0" : r["MinStock"].ToString());
                        soQty = double.Parse(r["SOQty"].ToString().Length == 0 ? "0" : r["SOQty"].ToString());
                        poQty = double.Parse(r["POQty"].ToString().Length == 0 ? "0" : r["POQty"].ToString());
                        inHand = double.Parse(r["InHand"].ToString().Length == 0 ? "0" : r["InHand"].ToString());
                        mrp = fc + minStock + soQty - poQty - inHand;
                        if (mrp <= 0)
                        {
                            continue;
                        }
                        DataRow rNew = dt.NewRow();
                        rNew["No"] = r["No"];
                        rNew["U_ModelSales"] = r["U_ModelSales"];
                        rNew["U_ProductSales"] = r["U_ProductSales"];
                        rNew["ModelName"] = r["ModelName"];
                        rNew["ProductName"] = r["ProductName"];
                        rNew["VendorCode"] = r["CardCode"].ToString().Length == 0 ? "N/A" : r["CardCode"].ToString();
                        rNew["VendorName"] = r["CardName"].ToString().Length == 0 ? "N/A" : r["CardName"].ToString();
                        rNew["ForeCastQty"] = fc.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        rNew["MinStock"] = minStock.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        rNew["SOQty"] = soQty.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        rNew["POQty"] = poQty.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        rNew["InHand"] = inHand.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        rNew["MRP"] = mrp.ToString(Utils.AppConstants.NUMBER_FORMAT);
                        dt.Rows.Add(rNew);
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
            return dt;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["MRP"] = tblData;
            this.grvFCT1.DataSource = tblData;
            this.grvFCT1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadForeCastList()
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                MasterData obj = new MasterData();
                DataSet ds = obj.GetMRP(dbType);

                if (ds != null)
                {
                    this.drlForecast.DataSource = ds;
                    this.drlForecast.DataTextField = "Code";
                    this.drlForecast.DataValueField = "AbsID";
                    this.drlForecast.DataBind();
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool checkScenarion()
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                MasterData obj = new MasterData();
                DataSet ds = obj.CheckMRPScenario(dbType, this.txtScenarioName.Text);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtScenarioName.Text.Trim().Length == 0)
                {
                    this.txtScenarioName.Focus();
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Pls enter Scenario Code." + "','');", true);
                    return;
                }
               
                DataTable tbDetail = (DataTable)Session["MRP"];
                if (tbDetail != null)
                {
                    DataSet ds = new DataSet();

                    DataTable tbHeader = new DataTable();
                    tbHeader.Columns.Add("RunDate");
                    tbHeader.Columns.Add("FromDate");
                    tbHeader.Columns.Add("ToDate");
                    tbHeader.Columns.Add("AbsID");
                    tbHeader.Columns.Add("ForeCastCode");
                    tbHeader.Columns.Add("Remarks");
                    tbHeader.Columns.Add("ScenarioName");
                    tbHeader.Columns.Add("ScenarioDesc");
                    tbHeader.Columns.Add("DealerId");
                    tbHeader.Columns.Add("U_Department");
                    tbHeader.Columns.Add("WhsCode");

                    DateTime startdate = Utils.AppConstants.ConvertToDate("01/" + this.txtDateFrom.Text).Date;
                    DateTime enddate = Utils.AppConstants.ConvertToDate("01/" + this.txtDateTo.Text).Date;
                    DateTime deliveryDate = new DateTime(int.Parse(this.txtDateTo.Text.Substring(3, 4)), int.Parse(this.txtDateTo.Text.Substring(0, 2)),
                        DateTime.DaysInMonth(int.Parse(this.txtDateTo.Text.Substring(3, 4)), int.Parse(this.txtDateTo.Text.Substring(0, 2))));

                    DataRow rHeader = tbHeader.NewRow();
                    rHeader["RunDate"] = DateTime.Now;
                    rHeader["FromDate"] = startdate;
                    rHeader["ToDate"] = enddate;
                    rHeader["AbsID"] = this.drlForecast.SelectedValue;
                    rHeader["ForeCastCode"] = this.drlForecast.SelectedItem.Text;
                    rHeader["Remarks"] = this.txtRemarks.Text;
                    rHeader["ScenarioName"] = this.txtScenarioName.Text;
                    rHeader["ScenarioDesc"] = this.txtScenatioDesc.Text;
                    rHeader["DealerId"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                    rHeader["U_Department"] = Session[Utils.AppConstants.U_Department].ToString();
                    if (Session[Utils.AppConstants.WhsCode] != null)
                    {
                        rHeader["WhsCode"] = Session[Utils.AppConstants.WhsCode].ToString();
                    }
                    tbHeader.Rows.Add(rHeader);

                    tbHeader.TableName = "U_MRP_Header";
                    tbDetail.TableName = "U_MRP_Detail";

                    ds.Tables.Add(tbHeader);
                    ds.Tables.Add(tbDetail.Copy());

                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    MasterData obj = new MasterData();
                    string errorMess = obj.UpdateMRP(ds, dbType);
                    if (errorMess.Length > 0)
                    {
                        this.lblError.Text = errorMess;
                    }
                    else
                    {

                        DataTable tbMRP = (DataTable)Session["MRP"];
                        DataSet dsPO = new DataSet();
                        if (tbMRP != null)
                        {
                            foreach (DataRow r in tbMRP.Rows)
                            {
                                DataTable tbTemp = tbMRP.Clone();
                                if (dsPO.Tables.Contains(r["VendorCode"].ToString()))
                                {
                                    dsPO.Tables[r["VendorCode"].ToString()].ImportRow(r);
                                }
                                else
                                {
                                    tbTemp.TableName = r["VendorCode"].ToString();
                                    tbTemp.ImportRow(r);
                                    dsPO.Tables.Add(tbTemp);
                                }
                            }
                        }

                        DataSet dsUpdatePO = new DataSet();
                        if (dsPO != null && dsPO.Tables.Count > 0)
                        {

                            foreach (DataTable tb in dsPO.Tables)
                            {
                                DataTable dtHeader = new DataTable("U_MRP_POHeader");
                                dtHeader.Columns.Add("DocEntry");
                                dtHeader.Columns.Add("DocNum");
                                dtHeader.Columns.Add("Series");
                                dtHeader.Columns.Add("DocStatus");
                                dtHeader.Columns.Add("DocDate");
                                dtHeader.Columns.Add("DocDueDate");
                                dtHeader.Columns.Add("TaxDate");
                                dtHeader.Columns.Add("CardCode");
                                dtHeader.Columns.Add("CardName");
                                dtHeader.Columns.Add("Comments");
                                dtHeader.Columns.Add("DocTotal");
                                dtHeader.Columns.Add("ScenarioCode");
                                dtHeader.Columns.Add("DealerId");
                                dtHeader.Columns.Add("U_SOType");
                                dtHeader.Columns.Add("U_Department");
                                dtHeader.Columns.Add("WhsCode");

                                DataRow drHeader = dtHeader.NewRow();
                                drHeader["Series"] = 13;
                                drHeader["DocStatus"] = "O";
                                drHeader["DocDate"] = DateTime.Now.ToString("yyyyMMdd");
                                drHeader["DocDueDate"] = DateTime.Now.ToString("yyyyMMdd");
                                drHeader["TaxDate"] = DateTime.Now.ToString("yyyyMMdd");
                                drHeader["Comments"] = txtRemarks.Text;
                                drHeader["CardCode"] = tb.TableName;
                                drHeader["CardName"] = tb.Rows[0]["VendorName"].ToString();
                                drHeader["U_SOType"] = "0";
                                drHeader["ScenarioCode"] = this.txtScenarioName.Text.Trim();
                                drHeader["DealerId"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                                drHeader["U_Department"] = Session[Utils.AppConstants.U_Department].ToString();
                                if (Session[Utils.AppConstants.WhsCode] != null)
                                {
                                    drHeader["WhsCode"] = Session[Utils.AppConstants.WhsCode].ToString();
                                }

                                DataTable dtDetail = new DataTable("U_MRP_PODetail");
                                dtDetail.Columns.Add("DocEntry");
                                dtDetail.Columns.Add("LineNum");
                                dtDetail.Columns.Add("LineStatus");
                                dtDetail.Columns.Add("U_ModelSales");
                                dtDetail.Columns.Add("U_ProductSales");
                                dtDetail.Columns.Add("UomCode");
                                dtDetail.Columns.Add("Quantity");
                                dtDetail.Columns.Add("PriceBefDi");
                                dtDetail.Columns.Add("DiscPrcnt");
                                dtDetail.Columns.Add("Price");
                                dtDetail.Columns.Add("LineTotal");
                                dtDetail.Columns.Add("TaxCode");
                                dtDetail.Columns.Add("OrderQty");
                                foreach (DataRow dr in tb.Rows)
                                {
                                    DataRow rDetail = dtDetail.NewRow();

                                    rDetail["U_ModelSales"] = dr["U_ModelSales"];
                                    rDetail["U_ProductSales"] = dr["U_ProductSales"];
                                    DataRow row = dtDetail.NewRow();
                                    rDetail["LineStatus"] = "O";
                                    rDetail["Quantity"] = dr["MRP"];
                                    rDetail["OrderQty"] = 0;
                                    dtDetail.Rows.Add(rDetail);
                                }

                                dtHeader.Rows.Add(drHeader);
                                dsUpdatePO.Tables.Add(dtHeader);
                                dsUpdatePO.Tables.Add(dtDetail);
                                string errMess = obj.UpdatePOMRP(dsUpdatePO, dbType);
                            }
                        }
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                        this.txtScenarioName.Text = "";
                        this.txtScenatioDesc.Text = "";
                        this.txtRemarks.Text = "";
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Can not save MRP." + "','');", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="AbsID"></param>
        /// <param name="NewDocType"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        private void LoadData(string AbsID, string dbType, DateTime startDate, DateTime endDate, DateTime deliveryDate)
        {
            try
            {
                GeneralFunctions GF = null;
                string strWH = string.Empty;
                GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                StringBuilder wareHouse = new StringBuilder();
                if (Session[Utils.AppConstants.WhsCode] != null)
                {
                    strWH = Session[Utils.AppConstants.WhsCode].ToString();
                }
                else
                {
                    DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.SALES);
                    if (dtWhs != null)
                    {
                        foreach (DataRow r in dtWhs.Rows)
                        {
                            wareHouse.Append(r["WhsCode"].ToString());
                            wareHouse.Append(",");
                        }
                        strWH = wareHouse.ToString().Substring(0, wareHouse.ToString().Length - 1);
                    }
                }

                MasterData obj = new MasterData();
                DataSet returnDoc = obj.GetMRPByAbsID(dbType, AbsID, startDate, endDate, deliveryDate, strWH);
                if (returnDoc != null && returnDoc.Tables.Count > 0)
                {
                    DataTable dtContents = BuildContents(returnDoc.Tables[0]);
                    BindData(dtContents);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Can not found data." + "','');", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DateTime startdate = Utils.AppConstants.ConvertToDate("01/" + this.txtDateFrom.Text).Date;
                DateTime enddate = Utils.AppConstants.ConvertToDate("01/" + this.txtDateTo.Text).Date;
                DateTime deliveryDate = new DateTime(int.Parse(this.txtDateTo.Text.Substring(3, 4)), int.Parse(this.txtDateTo.Text.Substring(0, 2)),
                    DateTime.DaysInMonth(int.Parse(this.txtDateTo.Text.Substring(3, 4)), int.Parse(this.txtDateTo.Text.Substring(0, 2))));
                LoadData(this.drlForecast.SelectedValue.ToString(), dbType, startdate, deliveryDate, deliveryDate);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
            }
        }
    }
}